package com.csxy.six.util;

import com.csxy.six.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtUtils jwtUtils;

    public JwtAuthenticationFilter(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String token = extractToken(request);
        if (token != null) {
            try {
                // 使用 JwtUtils 的 validateToken 方法（如果存在）
                // 如果不存在，使用替代方法验证
                if (isTokenValid(token)) {
                    String userId = getUserIdFromToken(token);
                    if (userId != null) {
                        UserDetails userDetails = createUserDetails(userId);
                        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                                userDetails, null, userDetails.getAuthorities());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                    }
                }
            } catch (Exception e) {
                // 令牌无效，忽略
            }
        }
        filterChain.doFilter(request, response);
    }

    private String extractToken(HttpServletRequest request) {
        String header = request.getHeader("Authorization");
        if (header != null && header.startsWith("Bearer ")) {
            return header.substring(7);
        }
        return null;
    }

    private boolean isTokenValid(String token) {
        try {
            // 尝试解析令牌来验证有效性
            getUserIdFromToken(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    private String getUserIdFromToken(String token) {
        try {
            // 尝试解析令牌获取用户ID
            Claims claims = jwtUtils.parseToken(token); // 如果存在这个方法
            return claims.getSubject();
        } catch (Exception e) {
            // 如果 parseToken 方法不存在，使用替代方法
            return extractUserIdFromToken(token);
        }
    }

    private String extractUserIdFromToken(String token) {
        // 这里实现自定义的令牌解析逻辑
        // 这只是一个示例，实际应用中需要根据您的令牌格式实现
        try {
            // 示例：假设令牌格式是 "userid:timestamp:signature"
            String[] parts = token.split(":");
            if (parts.length > 0) {
                return parts[0];
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }

    private UserDetails createUserDetails(String userId) {
        // 这里应该从数据库加载用户详情，简化版只创建基本对象
        return new org.springframework.security.core.userdetails.User(
                userId, "", java.util.Collections.emptyList());
    }
}